<?php
/*
*后台页面展示
*/
/** * * ━━━━━━神兽出没━━━━━━
*       ┌─┐      ┌─┐
*     ┌─┘─┴──────┘─┴─┐
*     │              │
*     │      ─       │
*     │  ┬─┘   └─┬   │
*     │              │
*     │      ┴       │
*     │              │
*     └───┐      ┌───┘
*         │      │Code is far away from bug with the animal protecting ！
*         │      │神兽保佑,代码无bug！
*         │      └──────┐
*         │             ├┐
*         │             ┌┘
*         └┐ ┐ ┌───┬─┐ ┌┘
*          │ ┤ ┤   │ ┤ ┤
*          └─┴─┘   └─┴─┘
* ━━━━━━感觉萌萌哒━━━━━━
*/
namespace app\admin\controller;
use think\Controller;
use think\Request;
use \think\Db;
class User extends Base{


	  public function _initialize() {
        parent::_initialize ();
      }
     //加盟商列表
     public function index(){
      $data = $this->data;
      $where = ['s.del_status'=>0];
      if(isset($data['ischeck']) && !empty($data['ischeck'])){
        $where['s.ischeck']= $data['ischeck'];
      }
      $field = "s.id,s.name,u.username,s.uid,u.pid,u.phone,s.province,s.city,s.district,s.ischeck";
      $list = Db::name("shop")->alias("s")->join("jun_user u","u.id=s.uid","left")->where($where)->field($field)->paginate(10);
      if(!empty($list)){
        $data = $list->all();
        foreach ($data as $key => $value) {
          $value["manager_num"] = Db::name(self::$tb['user'])->alias("u")
          ->join("jun_role r","r.id = u.role_id","left")->where(["u.shop_id"=>$value['id'],"r.name"=>"业务经理"])->count("u.id");
          $list[$key] = $value;
        }
      }
      $page = $list->render();
      $this->assign("list",$list);
      $this->assign("page",$page);
     	return $this->fetch();
     }

    /*
    *加入回收站
    */
     public function deleteshop()
     {
       $data = $this->data;
       $where = ['del_status'=>0,'id'=>$data['id']];
       $id = Db::name(self::$tb['shop'])->where($where)->value("id");
       if(!$id){
        $this->error("操作失败");
       }else{
         $res= Db::name(self::$tb['shop'])->where($where)->update(['del_status'=>1]);
         if($res){
          $this->success("操作成功");
         }else{
          $this->error("操作失败");
         }
       }
     }


    /**
    * 店铺详情
    */
    public function edit_shop(){
       $data = $this->data;
       if(isset($data['id']) && !empty($data['id'])){
         $where = ['s.id'=>$data['id']];
         $field = "s.id,u.username,u.pid,u.phone,u.join_money,u.identify,s.name,s.province,s.city,s.district,s.detail,
         s.addtime,s.shop_pic,s.business_pic,s.business_card,s.identify_picp,s.identify_picb";
         $detail = Db::name(self::$tb['shop'])->alias("s")->join("jun_user u","u.id=s.uid","left")->where($where)->field($field)->find();
         $this->assign("detail",$detail);
       }
        $province_list = $this->getProvinceList();
        $this->assign("province_list",$province_list);
        return $this->fetch();
    }


    /*
    * 编辑店铺
    */
    public function shop_edit(){
       $data = $this->data;
       Db::startTrans();
      try{
       if(isset($data['id']) && !empty($data['id'])){
        $where=["id",$data['id']];
        $exist = Db::name(self::$tb['shop'])->where($where)->field("id,uid")->find();
        if(!$exist){
          //修改
           $update_shop = [
              "name"=>$data['name'],
              "province"=>isset($data['province'])??'',
              "city"=>isset($data['city'])??'',
              "district"=>isset($data['district'])??'',
              "detail"=>isset($data['detail'])??'',
              "shop_pic"=>$data['shop_pic'],
              "business_pic"=>$data['business_pic'],
              "business_card"=>$data['business_card'],
              "identify_picp"=>$data['identify_picp'],
              "identify_picb"=>$data['identify_picb'],
              "commit_id"=>session("user_id")??'',
              "addtime"=>time(),
              "ischeck"=>1,
           ];
           $res= Db::name(self::$tb['shop'])->where($where)->update($update_shop);
        }else{
           $this->error("该用户不存在");
        }
       }else{
        $insert_shop = [
          "name"=>$data['name'],
          "province"=>isset($data['province'])??'',
          "city"=>isset($data['city'])??'',
          "district"=>isset($data['district'])??'',
          "detail"=>isset($data['detail'])??'',
          "shop_pic"=>$data['shop_pic'],
          "business_pic"=>$data['business_pic'],
          "business_card"=>$data['business_card'],
          "identify_picp"=>$data['identify_picp'],
          "identify_picb"=>$data['identify_picb'],
          "commit_id"=>session("user_id")??'',
          "addtime"=>time(),
          "ischeck"=>1,
        ];
        $shop_id = Db::name(self::$tb['shop'])->insertGetId($insert_shop);
        $insert_user = [
          "name"=>$data['name'],
          "username"=>$data['username'],
          "password"=>md5("123456"),
          "phone"=>$data['phone'],
          "shop_id"=>$shop_id,
          "identify"=>$data['identify'],
          "identify_picp"=>$data['identify_picp'],
          "identify_picb"=>$data['identify_picb'],
          "province"=>isset($data['province'])??'',
          "city"=>isset($data['city'])??'',
          "district"=>isset($data['district'])??'',
          "detail"=>isset($data['detail'])??'',
          "ischeck"=>1,
          "join_money"=>$data['join_money'],
          "role_id"=>2,
        ];
        $res = Db::name(self::$tb['user'])->insert($insert_user);
       }
        Db::commit();
        $this->success("操作成功");
      } catch (\Exception $e) {
        Db::rollback();
        throw($e);
        $this->error("操作失败");
      }

    }


    /**
    *审核通过店铺
    */
    public function commit_shop(){
       $data = $this->data;
       $commit = session("user_id");
       $uid = Db::name(self::$tb['shop'])->where("id",$data['id'])->value("uid");
       if($uid){
         $update = [
          "commit_id"=>$commit['id'],
          "ischeck"=>1,
          "commit_time"=>time()
         ];
         $result = Db::name(self::$tb['shop'])->where("id",$data['id'])->update($update);
         if($result){
           $update['enable'] = 1;
          Db::name(self::$tb['user'])->where("id",$uid)->update($update);
          $this->success("操作成功");

         }else{
            $this->error("操作失败");
         }
       }else{
            $this->error("不存在记录");
       }
    }



    /**
    *用户列表
    */
    public function user_list(){
       $data = $this->data;
       $where = [
          "u.enable"=>1,
          "u.shop_id"=>$data["id"],
          "u.del_status"=>0
       ];
       if(isset($data['ischeck']) && !empty($data['ischeck'])){
        $where['u.ischeck'] = $data['ischeck'];
       }
      //姓名查询
      if(isset($data['name']) && !empty($data['name'])){
        $where['u.name'] = ["like","%{$data['name']}%"];
      }
      //手机查询
      if(isset($data['phone']) && !empty($data['phone'])){
        $where['u.phone'] = ["like","%{$data['phone']}%"];
      }
      $where['r.name'] = "业务经理";
      $field="u.id,u.name,u.username,u.pid,phone,identify,identify_picp,identify_picb,province,
      city,detail,district,ischeck,join_money,sale_total,flow_money,ischeck";
      $list=Db::name(self::$tb['user'])->alias("u")->join("jun_role r","u.role_id=r.id")
      ->where($where)->field($field)->paginate(10,true);
      $datas = $list->all();
      foreach ($datas as $key => $value) {
        $value["sale_num"] = Db::name(self::$tb['user'])->where("pid",$value['id'])->count();
        $value['order_num'] = Db::name(self::$tb['order'])->where("uid",$value['id'])->count();
        $value['customer_num'] = Db::name(self::$tb['member'])->where("cs_id",$value['id'])->count();
        $list[$key] = $value;
      }
      $page = $list->render();
      $this->assign("shop_id",$data['id']);
      $this->assign("list",$list);
      $this->assign("page",$page);
      return $this->fetch();
    }


    public function adduser(){
       $data = $this->data;
       if(isset($data['id']) && !empty($data['id'])){
        $dtail = Db::name(self::$tb['member'])->where("id",$data['id'])->find();
        $this->assign("detail",$dtail);
       }
       $shop_list= Db::name(self::$tb['shop'])->where(["ischeck"=>1,"del_status"=>0])->field("id,name")->select();
       $this->assign("shop_list",$shop_list);
       $province_list = $this->getProvinceList();
       $this->assign("province_list",$province_list);
       return $this->fetch("user/adduser");
    }
    /*
    *获取用户详情
    */
    public function edit_user(){
      $data = $this->data;
      if(isset($data['id']) && !empty($data['id'])){
        $where = ["u.id"=>$data['id']];
        $field = "u.id,u.name,u.shop_id,u.username,u.phone,u.identify,u.identify_picp,u.identify_picb,u.province,u.city,
        u.district,u.detail,u.ischeck,u.join_money,u.enable,u.commit_time,u.sale_total,u.addtime,r.name as role_name,c.name as commit_name";
        $detail = Db::name(self::$tb['user'])->alias("u")->join("jun_role r","r.id=u.role_id","left")->join("jun_user c","c.id =u.commit_id","left")->where($where)->field($field)->find();
        $detail['shop_name'] = Db::name(self::$tb['shop'])->where("id",$detail['shop_id'])->value("name");
        $this->assign("detail",$detail);
      }
      $province_list = $this->getProvinceList();
      $this->assign("province_list",$province_list);
      $this->assign("shop_id",$data['shop_id']);
      return $this->fetch();
    }


    /**
    *用户列表
    */
    public function sale_list(){
       $data = $this->data;
       $where = [
          "u.enable"=>1,
          "u.pid"=>$data["id"],
          "u.del_status"=>0
       ];
       if(isset($data['ischeck']) && !empty($data['ischeck'])){
        $where['u.ischeck'] = $data['ischeck'];
       }
      //姓名查询
      if(isset($data['name']) && !empty($data['name'])){
        $where['u.name'] = ["like","%{$data['name']}%"];
      }
      //手机查询
      if(isset($data['phone']) && !empty($data['phone'])){
        $where['u.phone'] = ["like","%{$data['phone']}%"];
      }
      $where['r.name'] = "业务员";
      $field="u.id,u.name,u.username,u.pid,phone,identify,identify_picp,identify_picb,province,
      city,detail,district,ischeck,join_money,sale_total,flow_money,ischeck";
      $list=Db::name(self::$tb['user'])->alias("u")->join("jun_role r","u.role_id=r.id")
      ->where($where)->field($field)->paginate(10,true);
      $datas = $list->all();
      foreach ($datas as $key => $value) {
        $value["sale_num"] = Db::name(self::$tb['user'])->where("pid",$value['id'])->count();
        $value['order_num'] = Db::name(self::$tb['order'])->where("uid",$value['id'])->count();
        $value['customer_num'] = Db::name(self::$tb['member'])->where("cs_id",$value['id'])->count();
        $list[$key] = $value;
      }
      $page = $list->render();
      $this->assign("pid",$data['id']);
      $this->assign("shop_id",$data['shop_id']);
      $this->assign("list",$list);
      $this->assign("page",$page);
      return $this->fetch();
    }



    /*
    *编辑用户信息
    */
     public function user_edit(){
       $data = $this->data;
       if(isset($data['id']) && !empty($data['id'])) {
          //更新用户信息
          $update = [
           "name"=>$data['name'],
           "phone"=>$data['phone'],
           "enable"=>$data['enable'],
           "identify"=>$data['identify'],
           "province"=>$data['province']??'',
           "city"=>$data['city']??'',
           "district"=>$data['district']??'',
           "detail"=>$data['detail']??'',
           "identify_picp"=>$data['identify_picp']??'',
           "identify_picb"=>$data['identify_picb']??'',
           "join_money"=>$data['join_money']??''
          ];
          $res = Db::name(self::$tb['user'])->where("id",$data['id'])->update($update);
       }else{
          $insert = [
           "name"=>$data['name'],
           "phone"=>$data['phone'],
           "shop_id"=>$data['shop_id'],
           "pid"=>$data['pid']??0,
           "username"=>$data['username'],
           "enable"=>$data['enable'],
           "identify"=>$data['identify'],
           "province"=>$data['province']??'',
           "city"=>$data['city']??'',
           "district"=>$data['district']??'',
           "detail"=>$data['detail']??'',
           "password"=>md5("123456"),
           "identify_picp"=>$data['identify_picp']??'',
           "identify_picb"=>$data['identify_picb']??'',
           "join_money"=>$data['join_money']??'',
           "addtime"=>time()
          ];
          if(isset($data['pid']) && !empty($data['pid'])){
              $insert['role_id'] = 3;   //业务员
          }else{
              $insert['role_id'] = 2;  //业务经理
          }
          $res = Db::name(self::$tb['user'])->insert($insert);
       }
         if($res){
          $this->success("操作成功","User/user_list/id/".$data['shop_id']);
         }else{
          $this->error("操作失败");
         }
     }

    /**
    *审核通过用户
    */
    public function commit_user(){
       $data = $this->data;
       $commit = session("user_id");
       $uid = Db::name(self::$tb['user'])->where("id",$data['id'])->value("id");
       if($uid){
         $update = [
          "commit_id"=>$commit['id'],
          "ischeck"=>1,
          "enable"=>1,
          "commit_time"=>time()
         ];
         $result = Db::name(self::$tb['user'])->where("id",$data['id'])->update($update);
         if($result){
          $this->success("操作成功");
         }else{
            $this->error("操作失败");
         }
       }else{
            $this->error("不存在记录");
       }
    }

    /**
    *用户加入回收站
    */
    public function deleteuser(){
       $data = $this->data;
       $where = ['del_status'=>0,'id'=>$data['id']];
       $id = Db::name(self::$tb['user'])->where($where)->value("id");
       if(!$id){
        $this->error("操作失败");
       }else{
         $res= Db::name(self::$tb['user'])->where($where)->update(['del_status'=>1]);
         if($res){
          $this->success("操作成功");
         }else{
          $this->error("操作失败");
         }
       }
    }


 /**
   * 获取省份
   */
   public function getProvinceList(){
      $sql = "select areaid,areaname,rowid,parentrowid from jun_area where char_length(areaid)=3";
      $province_list = Db::query($sql);
      return $province_list;

   }

    /**
    * 获取城市列表
    */
   public function getCityList(){
      $data = $this->data;
      $where['parentrowid'] = $data['rowid'];
      $field = "areaid,areaname,rowid,parentrowid";
      $city_list = Db::name(self::$tb['area'])->where($where)->field($field)->select();
      return api_return(10001,$city_list);
   }


  /*获取业务经理列表*/
   public function getManagerList(){
     $data = $this->data;
     $where = [
      "u.shop_id"=>$data['shop_id'],
      "r.name"=>"业务经理",
     ];
     $list = Db::name(self::$tb['user'])->alias("u")->join("jun_role r","r.id =u.role_id","left")->where($where)->field("u.id,u.name")->select();
     return api_return(10002,$list);
   }

   /*获取业务员列表*/
   public function getSaleList(){
      $data = $this->data;
      $where = ["pid"=>$data['pid']];
      $list = Db::name(self::$tb['user'])->where($where)->field("id,name")->select();
      return api_return(10002,$list);
   }


  /*编辑会员*/
  public function edit_member(){
    $data = $this->data;
    $data['member_id'] = $data['member_id'];
    $data['pid'] = isset($data['pid'])?$data['pid']:0;
      $insert = [
        "name" =>$data['name'],
        "phone" =>$data['phone'],
        "identify_picp" =>$data['identify_picp'],
        "identify_picb" =>$data['identify_picb'],
        "identify" =>$data['identify'],
        "pid" =>0,
        "province" =>$data['province']??"",
        "city" =>$data['city']??"",
        "district" =>$data['district']??"",
        "detail" =>$data['detail']??"",
        "join_money" =>$data['join_money']??0,
        "role_id" =>1,
        "is_user" =>1,
        "user_id" =>$data['member_id'],
        "addtime"=>time(),
      ];
     Db::startTrans();
     try{
      if($data['role_type'] == 1){  //申请加盟商
         $result = Db::name(self::$tb['user'])->insertGetId($insert);
          $insert_shop = [
            "name" =>$data['name'],
            "phone" =>$data['phone'],
            "uid" =>$result,
            "province" =>$data['province']??"",
            "city" =>$data['city']??"",
            "identify_picp" =>$data['identify_picp'],
            "identify_picb" =>$data['identify_picb'],
            "identify" =>$data['identify'],
            "business_card" =>$data['business_card'],
            "business_pic" =>$data['business_pic'],
            "district" =>$data['district']??"",
            "detail" =>$data['detail']??"",
            "addtime"=>time(),
          ];
          $shop = Db::name(self::$tb['shop'])->insertGetId($insert_shop);
          $res = Db::name(self::$tb['user'])->where("id",$result)->update(["shop_id"=>$shop]);
        }else if($data['role_type'] == 2){
          $insert['role_id'] = 2;
          $res = Db::name(self::$tb['user'])->insert($insert);
        }else if($data['role_type'] == 2){
          $insert['role_id'] = 3;
          $res = Db::name(self::$tb['user'])->insert($insert);
        }
        Db::commit();
        $this->success("操作成功");
      } catch (\Exception $e) {
        Db::rollback();
        throw($e);
        $this->error("操作失败");
      }

  }

   public function member_list(){
      $data = $this->data;
      $where = [];
      $field = "m.id,m.name,m.mobile,m.province,m.city,m.district,m.detail,m.addtime,m.sex,u.name as cs_name";
      $list = Db::name(self::$tb['member'])->alias("m")->join("jun_user u","u.id=m.cs_id","left")->where($where)->field($field)->paginate(10);
      $page = $list->render();
      $this->assign("list",$list);
      $this->assign("page",$page);
      return $this->fetch();
   }

  //通用异步上传图片
  public function ajaxuploads(){
    $file = request()->file('file');
      if($file){
          $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
          if($info){
              $pic = '/uploads/'.$info->getSaveName();
          }
        $arr = [
            'status' =>'1',
            'path' =>$pic,
        ];
      }else{
        $arr = [
            'status' =>0,
            'path' =>"上传图片",
        ];
      }
      echo json_encode($arr);
  }



}
